import db from '@/utils/localstorage'
import {login} from '@/api/system/security'

export default {
  namespaced: true,
  state: {
    username: '',
    nickname: '',
    avatar: '',
    accessToken: db.get('ACCESS_TOKEN', ''),
    expireTime: db.get('EXPIRE_TIME', 0),
    userRouters: db.get('USER_ROUTERS', ''),
    userPermissions: db.get('USER_PERMISSIONS', '')
  },
  mutations: {
    setUsername (state, value) {
      state.username = value
      db.save('USERNAME', value)
    },
    setNickname (state, value) {
      state.nickname = value
      db.save('NICKNAME', value)
    },
    setAvatar (state, value) {
      state.avatar = value
      db.save('AVATAR', value)
    },
    setAccessToken (state, value) {
      state.token = value
      db.save('ACCESS_TOKEN', value)
    },
    setExpireTime (state, value) {
      state.expireTime = value
      db.save('EXPIRE_TIME', value)
    },
    setRouters (state, value) {
      state.userRouters = value
      db.save('USER_ROUTERS', value)
    },
    setPermissions (state, value) {
      state.userPermissions = value
      db.save('USER_PERMISSIONS', value)
    }
  },
  actions: {
    login ({commit}, loginForm) {
      const username = loginForm.username.trim()
      return new Promise((resolve, reject) => {
        login(username, loginForm.password).then(response => {
          const data = response.data
          commit('setAccessToken', data.token) // 登陆成功后将token存储在cookie中
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
